var express = require('express');
var router = express.Router();
var db = require('../../data');
var multiparty = require('multiparty');
var fs = require('fs');
var util = require('util');
var config = require('config');
/* GET home page. */

var GET = function(req, res, next){
  var session = req.session;
  var data = db.model;

  if(!session.user || !session.user.login){
    res.redirect('/admin/login');
  }else{

    data.basicFacts.findOne(function(err, data){

      var returnData = {
        path: 'index',
        basicFacts : data,
        user : session.user
      };

      res.render('admin/index', returnData);
    });

  };
};

var POST = function(req, res, next){
  var form = new multiparty.Form();
  form.parse(req, function(err, fields, files){

    fs.exists(config.dirname + "/public/upload/images/default.png", function(exists){
      if(!exists)
        fs.rename(config.dirname + "/public/upload/images/bg.png", config.dirname + "/public/upload/images/default.png", function(err){
          if(err)
            return next();
          else{
            var readStream = fs.createReadStream(files.file[0].path);
            var writeStream = fs.createWriteStream(config.dirname + "/public/upload/images/bg.png");

            util.pump(readStream, writeStream, function() {
              fs.unlink(files.file[0].path);
              res.redirect('/admin/index');
            });
          }
        });
      else{
        var readStream = fs.createReadStream(files.file[0].path);
        var writeStream = fs.createWriteStream(config.dirname + "/public/upload/images/bg.png");

        util.pump(readStream, writeStream, function() {
          fs.unlink(files.file[0].path);
          res.redirect('/admin/index');
        });
      }
    });
  });
};

router.get('/', GET);
router.get('/index', GET);
router.post('/index/upload', POST);

module.exports = router;
